package com.xmutca.core.websocket.handler;

import com.xmutca.core.websocket.ChannelFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Set;


@ChannelHandler.Sharable
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

	private final static Logger logger = LoggerFactory.getLogger(TextWebSocketFrameHandler.class);

	private ChannelFactory channelFactory;

	private WebSocketEventHandler webSocketEventHandler;

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, TextWebSocketFrame frame) throws Exception {
		String userId = channelFactory.getUserId(ctx.channel());

		//重构消息体
		String text = frame.text();

		//退出事件文本通知，默认不处理
		if("quit".equals(text)) {
			return;
		}

		if (webSocketEventHandler == null) {
			webSocketEventHandler = new WebSocketEventHandler();
		}

		//处理接收事件
		webSocketEventHandler.receive(this, userId, frame.text());
		logger.debug("用户：{} -> 发来新的消息:{}", userId, frame.text());
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

	//发送消息
	public void sendMessage(Collection<Channel> channels, String message) {
		if(channels != null) {
			TextWebSocketFrame tws = new TextWebSocketFrame(message);
			for (Channel channel : channels) {
				channel.writeAndFlush(tws);
			}
		}
	}

	//发送消息
	public void sendMessage(Channel channel, String message) {
		TextWebSocketFrame tws = new TextWebSocketFrame(message);
		channel.writeAndFlush(tws);
	}

	//发送消息
	public void sendMessage(String userId, String message) {
		//用户ID为空，判断这是广播请求
		if (userId == null) {
			sendMessage(message);
			return;
		}
		Set<Channel> sessions = channelFactory.getSession(userId);
		sendMessage(sessions, message);
	}

	//群发消息
	public void sendMessage(String message) {
		TextWebSocketFrame tws = new TextWebSocketFrame(message);
		channelFactory.getGroup().writeAndFlush(tws);
	}

	public void setChannelFactory(ChannelFactory channelFactory) {
		this.channelFactory = channelFactory;
	}

	public void setWebSocketEventHandler(WebSocketEventHandler webSocketEventHandler) {
		this.webSocketEventHandler = webSocketEventHandler;
	}
}